package com.zdp.item.rabbit.consumer;

import com.rabbitmq.client.Channel;
import com.zdp.common.constant.RabbitConstants;
import com.zdp.common.domain.rabbit.FreezeStockMessage;
import com.zdp.common.utils.JsonUtils;
import com.zdp.item.mapper.ItemsSpecMapperCustom;
import com.zdp.item.service.ItemSpecService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author sesshomaru
 * @date 2021/7/11 12:33
 */
@Slf4j
@Component
public class ItemStockConsumer {

    @Autowired
    private ItemSpecService itemSpecService;

    //TODO 配置死信队列
    @RabbitListener(queues = RabbitConstants.FREEZE_STOCK_QUEEN)
    public void freezeStockProcess(@Payload String message, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag, Channel channel) throws IOException {
        try {
            FreezeStockMessage freezeStockMessage = JsonUtils.jsonToPojo(message, FreezeStockMessage.class);
            itemSpecService.freezeStockFromRemain(freezeStockMessage);
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            //  将异常消息放入死信
            channel.basicNack(deliveryTag, false, false);
        }
    }
}
